package com.dys.service.impl;

import com.dys.entity.AirQuality;
import com.dys.entity.District;
import com.dys.form.AirAddForm;
import com.dys.form.AirUpdateForm;
import com.dys.mapper.AirMapper;
import com.dys.mapper.DistrictMapper;
import com.dys.service.AirService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @className: com.dys.service.impl.AirServiceImpl
 * @description: 空气质量指数实现类
 * @author: pine cone
 * @version: v1.0.0
 * @createTime: 2024/04/08 22:36
 */
@Service
public class AirServiceImpl implements AirService {

    @Autowired
    private DistrictMapper districtMapper;

    @Autowired
    private AirMapper airMapper;

    @Override
    public List<District> findDistrictList() {
        List<District> districtList = districtMapper.findAll();
        return districtList;
    }

    @Override
    public PageInfo<List<AirQuality>> findAirByDistrictIdAndPage(Integer page, Integer size, Integer districtId) {
        // 1.分页
        PageHelper.startPage(page, size);

        // 2.查询所有空气质量信息集合
        List<AirQuality> airList = airMapper.findBydDistrictId(districtId);

        // 3.封装pageInfo
        PageInfo<List<AirQuality>> pageInfo = new PageInfo(airList);

        // 4.返回
        return pageInfo;
    }

    @Override
    @Transactional
    public void add(AirAddForm airAddForm) {
        // 1.封装数据
        AirQuality air = new AirQuality();

        BeanUtils.copyProperties(airAddForm, air);

        // 2.添加数据
        int count = airMapper.insert(air);

        // 3.判断count
        if (count != 1) {
            System.out.println("【添加空气质量信息失败】");
            throw new RuntimeException("【添加空气质量】 添加失败");
        }
    }

    @Override
    @Transactional
    public void updateById(AirUpdateForm airUpdateForm) {
        // 1.封装数据
        AirQuality air = new AirQuality();

        BeanUtils.copyProperties(airUpdateForm, air);

        // 2.修改数据
        int count = airMapper.updateById(air);

        // 3.判断count
        if (count != 1) {
            System.out.println("【修改空气质量信息失败】");
            throw new RuntimeException("【修改空气质量】 修改失败");
        }
    }

    @Override
    @Transactional
    public void deleteById(Integer id) {
        // 1.删除
        int count = airMapper.deleteById(id);

        // 2.判断
        if (count != 1) {
            System.out.println("【删除空气质量信息失败】");
            throw new RuntimeException("【删除空气质量】 删除失败");
        }
    }
}
